<template>
    <el-form ref="loginFormRef" size="large" class="login-content-form" :model="loginForm" :rules="loginRules">
        <el-form-item class="login-animation1" prop="username">
            <el-input v-model="loginForm.username" text :placeholder="$t('message.account.accountPlaceholder1')" clearable autocomplete="off">
                <template #prefix>
                    <el-icon class="el-input__icon">
                        <ele-User />
                    </el-icon>
                </template>
            </el-input>
        </el-form-item>
        <el-form-item prop="password">
            <el-input
                v-model="loginForm.password"
                :type="showPassword ? 'text' : 'password'"
                :placeholder="$t('message.account.accountPlaceholder2')"
                autocomplete="off"
            >
                <template #prefix>
                    <el-icon class="el-input__icon">
                        <ele-Unlock />
                    </el-icon>
                </template>
                <template #suffix>
                    <i
                        class="iconfont el-input__icon login-content-password"
                        :class="showPassword ? 'icon-yincangmima' : 'icon-xianshimima'"
                        @click="showPassword = !showPassword"
                    />
                </template>
            </el-input>
        </el-form-item>
        <el-form-item prop="captchaCode">
            <el-input v-model="loginForm.captchaCode" text :placeholder="$t('message.account.accountPlaceholder3')" autocomplete="off">
                <template #prefix>
                    <el-icon class="el-input__icon">
                        <ele-Postcard />
                    </el-icon>
                </template>
                <template #suffix>
                    <el-image class="captcha" :src="`data:image/png;base64,${captchaInfo.captchaBase64}`" @click="initCaptcha" />
                </template>
            </el-input>
        </el-form-item>
        <el-form-item class="login-animation4">
            <el-button v-waves type="primary" class="login-content-submit" :loading="loading" @click="onLogin(loginFormRef)">
                <span>{{ $t('message.account.accountBtnText') }}</span>
            </el-button>
        </el-form-item>
    </el-form>
</template>
<script setup lang="ts">
import { reactive, computed, ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useI18n } from 'vue-i18n'
import { Loading } from '@/utils/loading'
import { useUserStore } from '@/stores/modules/userStore'
import { getCaptcha } from '@/api/auth'
import { Auth } from '@/api/auth/types'
import type { FormInstance, FormRules } from 'element-plus'

const route = useRoute()
const router = useRouter()
const { t } = useI18n()
const useStore = useUserStore()

//显示密码
const showPassword = ref(false)
const loading = ref(false)
const loginFormRef = ref<FormInstance>()
//校验
const loginRules = reactive<FormRules>({
    username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
    captchaCode: [{ required: true, message: '验证码不能为空', trigger: 'blur' }],
})
const loginForm = reactive<Auth.Form>({
    username: '',
    password: '',
    captchaId: '',
    captchaCode: '',
})
//登录
const onLogin = async (formEl: FormInstance | undefined) => {
    if (!formEl) {
        return
    }
    await formEl.validate(async (valid) => {
        if (!valid) {
            return
        }
        loading.value = true
        useStore
            .login(loginForm)
            .then((resp) => {
                console.log(resp)
                onSuccess()
            })
            .finally(() => {
                loading.value = false
            })
    })
}
/**
 * 登录成功
 */
const onSuccess = () => {
    // 初始化登录成功时间问候语
    const currentTimeInfo = currentTime.value
    if (route.query?.redirect) {
        router.push({
            path: <string>route.query?.redirect,
            // query: Object.keys(<string>route.query?.params).length > 0 ? JSON.parse(<string>route.query?.params) : '',
        })
    } else {
        router.push('/')
    }
    // 登录成功提示
    const signInText = t('message.signInText')
    ElMessage.success(`${currentTimeInfo}，${signInText}`)
    // 添加 loading，防止第一次进入界面时出现短暂空白
    Loading.start()
}

const captchaInfo = reactive<Auth.Captcha>({
    captchaId: '',
    captchaBase64: '',
})
//获取验证码
const initCaptcha = () => {
    getCaptcha().then((resp: Auth.Captcha) => {
        captchaInfo.captchaBase64 = resp.captchaBase64
        captchaInfo.captchaId = resp.captchaId
        loginForm.captchaId = resp.captchaId
    })
}

onMounted(() => {
    initCaptcha()
})
const currentTime = computed(() => {
    return new Date()
})
</script>
<style lang="scss" scoped>
.login-content-form {
    margin-top: 20px;
    .login-content-password {
        display: inline-block;
        width: 20px;
        cursor: pointer;
    }
    .login-content-code {
        width: 100%;
        padding: 0;
        font-weight: bold;
        letter-spacing: 5px;
    }

    .login-content-submit {
        width: 100%;
        letter-spacing: 2px;
        font-weight: 300;
        margin-top: 15px;
    }

    .captcha {
        cursor: pointer;
    }
}
</style>
